package com.project.collectAPI.comm;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.StringValue;
import com.project.collectAPI.entity.Firstclass;
import com.project.collectAPI.entity.Products;
import com.project.collectAPI.entity.Savedata;
import com.project.collectAPI.entity.Secondclass;
import com.project.collectAPI.service.FirstclassService;
import com.project.collectAPI.service.SavedataService;
import com.project.collectAPI.service.SecondclassService;
import okhttp3.Headers;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.SQLDataException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 抓包工具类
 */
/**
 * 抓包工具类
 */
public class SpiderTools {

    //ajax主机IP地址
    public static final String ServerIP= Constant.ServerIP;

    //当前抓取的店铺名称
    public static String StoreName="昌大昌鹰景店";


    private static CloseableHttpClient httpClient = HttpClients.createDefault();


    public static List<BasicNameValuePair> convertToEntity(Map<String, String> applicationParamsMap) throws Exception{
        ArrayList formParam = new ArrayList();
        try {
            if (applicationParamsMap != null) {
                Iterator var2 = applicationParamsMap.entrySet().iterator();

                while(var2.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var2.next();
                    BasicNameValuePair nameValuePair = new BasicNameValuePair((String)entry.getKey(),(String)entry.getValue());
                    formParam.add(nameValuePair);
                }
            }
            return formParam;
        } catch (Exception var5) {
            throw new Exception(var5);
        }
    }

    public static String requestOfPost(String url, Map<String, String> applicationParamsMap, byte[] fileData, String imgName, RequestConfig.Builder requestConfigBuilder) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfigBuilder.build());
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList();
            List<BasicNameValuePair> nameValuePairList =convertToEntity(applicationParamsMap);
            nameValuePairs.addAll(nameValuePairList);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, (String)null, Charset.forName("utf-8"));
            ByteArrayBody byteArray = new ByteArrayBody(fileData, imgName);
            entity.addPart("file", byteArray);
            URLEncodedUtils.format(nameValuePairs, "UTF-8");
            Iterator it = nameValuePairs.iterator();
            while(it.hasNext()) {
                NameValuePair param = (NameValuePair)it.next();
                entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName("utf8")));
            }
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            org.apache.http.HttpEntity responseEntity = response.getEntity();
            String var13 = EntityUtils.toString(responseEntity, "UTF-8");
            return var13;
        } catch (Exception var17) {
            throw new Exception(var17);
        } finally {
            httpPost.releaseConnection();
            if (response != null) {
                response.close();
            }
        }
    }

    //重载
    public static String requestOfPost(String url, Map<String, String> applicationParamsMap, RequestConfig.Builder requestConfigBuilder) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfigBuilder.build());
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList();
            List<BasicNameValuePair> nameValuePairList =convertToEntity(applicationParamsMap);
            nameValuePairs.addAll(nameValuePairList);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, (String)null, Charset.forName("utf-8"));
            URLEncodedUtils.format(nameValuePairs, "UTF-8");
            Iterator it = nameValuePairs.iterator();
            while(it.hasNext()) {
                NameValuePair param = (NameValuePair)it.next();
                entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName("utf8")));
            }
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            org.apache.http.HttpEntity responseEntity = response.getEntity();
            String var13 = EntityUtils.toString(responseEntity, "UTF-8");
            return var13;
        } catch (Exception var17) {
            throw new Exception(var17);
        } finally {
            httpPost.releaseConnection();
            if (response != null) {
                response.close();
            }
        }
    }



    public static String requestOfPostAsync(String url, Map<String, String> applicationParamsMap) throws Exception, IOException {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String var9;
        try {
            List<BasicNameValuePair> nameValuePairList = convertToEntity(applicationParamsMap);
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
            httpPost.setEntity(uefEntity);
            response = httpClient.execute(httpPost);
            org.apache.http.HttpEntity entity = response.getEntity();
            var9 = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var13) {
            throw new Exception(var13);
        } finally {
            httpPost.releaseConnection();
            if (response != null) {
                response.close();
            }

        }
        return var9;
    }


    public static String HttpGet(String url){
        //单位毫秒
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();//设置请求的状态参数

        CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);//返回请求执行结果
            int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            } else {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                //System.out.println("服务器响应:===>:"+result);
                return result;
            }
        } catch (Exception e) {
            System.out.println(("httpget Exception handle-- > " + e));
        } finally {
            if (response != null){
                try {
                    response.close();//关闭response
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
            if(httpclient != null){
                try {
                    httpclient.close();//关闭httpclient
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
        }
        return null;
    }









    public static String HttpGet(String url,String AuthStr){
        //单位毫秒
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();//设置请求的状态参数

        CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Authorization",AuthStr);
        httpGet.setHeader("Accept","application/json");
        httpGet.setHeader("User-Agent","https://zh.wikipedia.org/wiki/User_agent");

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);//返回请求执行结果
            int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            } else {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                //System.out.println("服务器响应:===>:"+result);
                return result;
            }
        } catch (Exception e) {
            System.out.println(("httpget Exception handle-- > " + e));
        } finally {
            if (response != null){
                try {
                    response.close();//关闭response
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
            if(httpclient != null){
                try {
                    httpclient.close();//关闭httpclient
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
        }
        return null;
    }


    /*
     *  表单 HttpPost请求
     *  List params=new ArrayList();
     *  //添加参数
     *  params.add(new BasicNameValuePair("键","值"));
     * */
    public static String HttpPost_MultipartFormData(String url, MultiValueMap<String, Object> body){

        System.out.println("传送的body===========>"+body);

        // 创建 RestTemplate 对象
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头信息
        HttpHeaders headers = new HttpHeaders();
        //MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
        //MediaType mediaType = MediaType.parseMediaType("multipart/form-data");
        //MediaType mediaType = MediaType.APPLICATION_FORM_URLENCODED;
        //headers.setContentType(mediaType);

        // 构造请求参数
            /*MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            FileSystemResource file1 = new FileSystemResource("path/to/file1");
            FileSystemResource file2 = new FileSystemResource("path/to/file2");
            body.add("files", file1);
            body.add("files", file2);

            //参考
            RequestEntity<byte[]> requestEntity = new RequestEntity<>(dataBytes, headers, HttpMethod.POST, URI.create("https://example.com/api"));
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
        */
        // 创建 HTTP POST 请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        /*MultiValueMap<String, String> requestEntity= new LinkedMultiValueMap<>();
        requestEntity.add("email", "844072586@qq.com");*/

        System.out.println("发送的url"+url);
        //ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
        System.out.println("服务器返回:=============>");
        System.out.println(response.getBody());
        return response.getBody().toString();



        /*ResponseEntity<String> respons = restTemplate.postForEntity(url, requestEntity, String.class);
        System.out.println("服务器返回1:=============>");
        System.out.println(respons.getBody());
        return respons.getBody();
        System.out.println(respons.getBody());
        return respons.getBody();
        */

        /*MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String requestJson = "{...}";
        HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);*/



        /*
            Map<String,String> map = new HashMap();
            map.put("start","1");
            map.put("page","5");
            String respons = restTemplate.postForObject(url, map, String.class,map);
            System.out.println("服务器返回222:=============>"+respons);
            return respons;
         */
    }



    public static String HttpPost(String url, List<NameValuePair> nameValues){
        //创建Http Post请求
        //HttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            //httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));

            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /*
     *  表单 HttpPost请求
     *  List params=new ArrayList();
     *  //添加参数
     *  params.add(new BasicNameValuePair("键","值"));
     * */
    public static String HttpPost(String url, Header[] Headers , List<NameValuePair> nameValues){
        //创建Http Post请求
        //HttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            //httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));
            httpPost.setHeaders(Headers);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
     * json HttpPost请求
     * */
    public static String HttpPostJson(String url, JSONObject json){
        //创建Http Post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json.toString(), StandardCharsets.UTF_8));
            httpPost.setHeader("accept","*/*");
            httpPost.setHeader("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpPost.setHeader("Content-type", "application/json"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
     * json HttpPost请求
     * */
    public static String HttpPostJson(String url,JSONObject json,String AuthorizationStr){
        System.out.println("签名信息========>"+AuthorizationStr);
        //创建Http Post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json.toString(), StandardCharsets.UTF_8));
            httpPost.setHeader("Authorization",AuthorizationStr);
            httpPost.setHeader("accept","*/*");
            httpPost.setHeader("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpPost.setHeader("Content-type", "application/json"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //ntpost.setEntity(new StringEntity(xml))
    /*
     *  表单 HttpPost请求 XML
     *  List params=new ArrayList();
     *  //添加参数
     *  params.add(new BasicNameValuePair("键","值"));
     * */
    public static Map<String,Object> HttpPostXML(String url, String xmlString){
        //创建Http Post请求
        //HttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            //httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));

            httpPost.setHeader("Content-type", "text/xml;charset=UTF-8"); //application/x-www-form-urlencoded  application/json
            //解决中文乱码问题
            StringEntity stringEntity = new StringEntity(xmlString,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            HttpResponse response = httpClient.execute(httpPost);
            String xmlData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+xmlData);
            if (!StringUtils.isEmpty(xmlData)) {
                System.out.println(XmlReader.xmlToMap(xmlData));
                return XmlReader.xmlToMap(xmlData);
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 返回Headers
     * @param HtmlString 解析到的Html字符串
     * */
    public static Map<String,String> getHeaders(String HtmlString) throws UnsupportedEncodingException {
        Map<String,String> res=new HashMap<>();
        String Host=getKeyValue("Host:\\s*.*",HtmlString).replaceAll("Host: ","").trim();
        String referer=getHttpUrl(getKeyValue("Referer:\\s*.*",HtmlString)).trim();
        String useragent=getKeyValue("User-Agent:\\s*.*",HtmlString).replaceAll("User-Agent: ","").trim();
        String origin=getKeyValue("Origin:\\s*.*",HtmlString).replaceAll("Origin: ","").trim();
        String cookie=getKeyValue("Cookie:\\s*.*",HtmlString).replaceAll("Cookie: ","").trim();
        System.out.println("Headers===>Host:===>"+Host);
        System.out.println("Headers===>referer:===>"+referer);
        System.out.println("Headers===>useragent:===>"+useragent);
        System.out.println("Headers===>Cookie:===>"+ cookie);
        //美团小程序专用解析
        res.put("Host",Host);
        res.put("Referer",referer);
        res.put("User-Agent",useragent);
        res.put("Origin",origin);
        res.put("cookie",cookie);
        return res;
    }

    /***
     * 查找指定字符串并分割获取指定值
     * @param patternStr
     * @param inputString
     * @return
     */
    public static String getKeyValue(String patternStr,String inputString){
        String rct="";
        //"Host:\\s*.*"
        //spiderTools.getKeyValue("User-Agent:\\s*.*", testStr);
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(inputString);
        if(matcher.find()) {
            rct=matcher.group();
            //System.out.println("找到："+rct);
        }
        return rct;
    }


    /***
     * 获取https正则
     * @param inputString
     * @return
     */
    public static String getHttpUrl(String inputString){
        String rct="";
        String patternStr="(http|https):.+";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(inputString);
        if(matcher.find()) {
            rct=matcher.group();
            //System.out.println("匹配的http："+rct);
        }
        return rct.replace("\n","").replace("\\n","");
    }

    /***
     * 查找2个{}之间的内容
     * @param inputString
     * @return
     */
    public static String getBracketsValue(String inputString){
        String rct="";
        String patternStr="\\{.+?\\}";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(inputString);
        if(matcher.find()) {
            rct=matcher.group();
            //System.out.println("匹配的{}："+rct);
        }
        return rct.replace("\n","").replace("\\n","");
    }


    /***
     * 获取body值
     * @param bodyString
     * @return
     */
    /*public static Map<String,String> getBodyValue(String bodyString){
        Map<String,String> listParas=new HashMap<>();
        if(bodyString.indexOf("&")!=-1){
            String[] arrs=bodyString.split("&");
            for(int i=0;i<arrs.length;i++){
                //content_personalized_switch=0
                //openidcipher=..省略wSUqknM6DYo/CwJsTzA== //注意后面有2个等于号
                String item=arrs[i];
                //String[] temp=item.split("=");
                String key=item.substring(0,item.indexOf("="));
                String val=item.substring(item.indexOf("=")+1,item.length());
                //System.out.println("key==>"+key+",val==>"+val);
                listParas.put(key,val);
            }
        }
        return listParas;
    }*/
    public static Map<String,String> getBodyValue(String bodyString){
        String bodyData=getKeyValue("djencrypt=\\s*.*",bodyString).replaceAll("djencrypt=","").trim();
        Map<String,String> listParas=new HashMap<>();
        listParas.put("djencrypt",bodyData);
        return listParas;
    }


    /**
     * 美团-post接口 获取url网页内容
     * @param baseUrl
     * @param headers
     *
     *
     */
    public static String getUrlContent(String baseUrl,Map<String,String> headers,String BodyData) throws IOException {
        Header[] Headers={
                new BasicHeader("Host",headers.get("Host")), //"wx-shangou.meituan.com"
                new BasicHeader("user-agent",headers.get("user-agent")), //"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF XWEB/6945"
                new BasicHeader("referer",headers.get("referer")), //https://servicewechat.com/wx2c348cf579062e56/812/page-frame.html
                new BasicHeader("sid",headers.get("sid").toString()), //{"a1":"1.2","a2":1686465297782,"a3":"8z17144883uu51x109446z344xy0776z811z10907wy97978183x3yzv","a4":"068283ca4c9c50e8ca838206e8509c4cbcbea8af54ee34e3","a5":"EVvmdJ/nKswkt0M99tzJY4jAwSY4+JHkK9LM9cbFnoPhaDhzegrQT3Ato2J5XPmvcbWWxoNkbXYS/2asz270kfh/mwYGSrCiL1yb0lOzgizW4VJoXsXAuZ4UmBSaooXUFgief2nh5y/sTwMrBGFWoheZ1SmHBjatYWYDwnorfXPOnOtjsRIJjCE9orB5B6UOL++Ke1S1tGolvLFGPXsmdzaRvkPY6I/m3B2ENMJVrvTV65CHj2Hgpjr=","a6":"w1.2LyeVc72vjdjQ5sHy4L/PAoGuiuwsI4RD6PMih6IeDuxLfybg8nTAuB4qLynUC0TOUkZMXB1aAQZb/TCDKLrtthOYyJDo+Vt4wDqylPHrks0kQNrouXTlzRcZZmgWKeJBokIBxGaJ7PUdA5/M4KoWvZVliUOPh+ciuR+6Ujd5U8DmuxV0rOG16tFNK2SoopxLK33hQLNM8cnGS6pNkl6jqLr6JP4tDdKHe29U9sADKPgC7x7quQqPcK40fRQmm49+4SHX6v2wnHkSZDQ0h7S8gb1LYgP05pOOX9ClvvZJtHkXODomX/g7vAMF4BkYwujZC4tbYjO8vNVmMB9QjB8vskB+l/a3Qo4WArKbNA271Uc4YF4ZP8tkTdSkkEhPbKLHurdeQCmWv+YxToAUei6ndelrjePnrm6AbVp7EXPjmrwSGlc9sje66+qTME2E5y+WNgfTwY0dJmf9Xt0yGDNmueguYFCRpoFuVjiMnbX+ks6Uvipko8xrBbiD29NZVVPU","a7":"wx2c348cf579062e56","x0":3,"d1":"cb3fa441965fb4230fffd78e5d2427e4"}
                new BasicHeader("Cookie",headers.get("cookie")), //"wx-shangou.meituan.com"
        };
        Map<String,String> BodyValue=getBodyValue(URLDecoder.decode(BodyData,"UTF-8")); //解码bodyData
        System.out.println("获取Body值===>"+ BodyValue.get("djencrypt").toString().trim());

        List<NameValuePair> nameValues=new ArrayList<NameValuePair>();
        nameValues.add(new BasicNameValuePair("djencrypt", BodyValue.get("djencrypt").toString().trim()));

        //打印
        /*System.out.println("baseUrl:"+baseUrl);
        System.out.println("打印Headers值【】========================================");
        for (int i=0;i<Headers.length;i++){
            System.out.println(Headers[i]);
        }
        System.out.println("打印nameValues值【】========================================");
        System.out.println("nameValues:"+nameValues);*/

        return HttpPost(baseUrl,Headers,nameValues);
        //return "你好";
    }


    /**
     * 美团-post接口 采集每间店铺菜单信息
     * @param baseUrl
     * @param headers
     *
     *
     */
    public static String getItemContent(String baseUrl,Map<String,String> headers,String BodyData) throws IOException {
       /*System.out.println("777777777777777 Host:"+headers.get("Host"));
        System.out.println("8888888888888888 user-agent:"+headers.get("user-agent"));
        System.out.println("9999999999999999 referer:"+headers.get("referer"));
        System.out.println("5555555555555555 mtgsig:"+headers.get("mtgsig"));*/
        Header[] Headers={
                new BasicHeader("Host",headers.get("Host")), //"wx-shangou.meituan.com"
                new BasicHeader("user-agent",headers.get("user-agent")), //"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF XWEB/6945"
                new BasicHeader("referer",headers.get("referer")), //https://servicewechat.com/wx2c348cf579062e56/812/page-frame.html
                new BasicHeader("mtgsig",headers.get("mtgsig").toString()), //{"a1":"1.2","a2":1686465297782,"a3":"8z17144883uu51x109446z344xy0776z811z10907wy97978183x3yzv","a4":"068283ca4c9c50e8ca838206e8509c4cbcbea8af54ee34e3","a5":"EVvmdJ/nKswkt0M99tzJY4jAwSY4+JHkK9LM9cbFnoPhaDhzegrQT3Ato2J5XPmvcbWWxoNkbXYS/2asz270kfh/mwYGSrCiL1yb0lOzgizW4VJoXsXAuZ4UmBSaooXUFgief2nh5y/sTwMrBGFWoheZ1SmHBjatYWYDwnorfXPOnOtjsRIJjCE9orB5B6UOL++Ke1S1tGolvLFGPXsmdzaRvkPY6I/m3B2ENMJVrvTV65CHj2Hgpjr=","a6":"w1.2LyeVc72vjdjQ5sHy4L/PAoGuiuwsI4RD6PMih6IeDuxLfybg8nTAuB4qLynUC0TOUkZMXB1aAQZb/TCDKLrtthOYyJDo+Vt4wDqylPHrks0kQNrouXTlzRcZZmgWKeJBokIBxGaJ7PUdA5/M4KoWvZVliUOPh+ciuR+6Ujd5U8DmuxV0rOG16tFNK2SoopxLK33hQLNM8cnGS6pNkl6jqLr6JP4tDdKHe29U9sADKPgC7x7quQqPcK40fRQmm49+4SHX6v2wnHkSZDQ0h7S8gb1LYgP05pOOX9ClvvZJtHkXODomX/g7vAMF4BkYwujZC4tbYjO8vNVmMB9QjB8vskB+l/a3Qo4WArKbNA271Uc4YF4ZP8tkTdSkkEhPbKLHurdeQCmWv+YxToAUei6ndelrjePnrm6AbVp7EXPjmrwSGlc9sje66+qTME2E5y+WNgfTwY0dJmf9Xt0yGDNmueguYFCRpoFuVjiMnbX+ks6Uvipko8xrBbiD29NZVVPU","a7":"wx2c348cf579062e56","x0":3,"d1":"cb3fa441965fb4230fffd78e5d2427e4"}
        };
        Map<String,String> BodyValue=getBodyValue(URLDecoder.decode(BodyData,"UTF-8")); //解码bodyData
        /*System.out.println("wm_logintoken===>"+BodyValue.get("wm_logintoken"));
        System.out.println("userToken===>"+BodyValue.get("userToken"));*/
        List<NameValuePair> nameValues=new ArrayList<NameValuePair>();
        if(!Objects.isNull(BodyValue.get("content_personalized_switch"))) {
            nameValues.add(new BasicNameValuePair("content_personalized_switch", BodyValue.get("content_personalized_switch").toString().trim()));
        }
        nameValues.add(new BasicNameValuePair("ad_personalized_switch", BodyValue.get("ad_personalized_switch").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_ctype", BodyValue.get("wm_ctype").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_dtype", BodyValue.get("wm_dtype").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_dversion", BodyValue.get("wm_dversion").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_uuid", BodyValue.get("wm_uuid").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_visitid", BodyValue.get("wm_visitid").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_appversion", BodyValue.get("wm_appversion").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_logintoken", BodyValue.get("wm_logintoken").toString().trim().replace(" ","+")));
        nameValues.add(new BasicNameValuePair("userToken", BodyValue.get("userToken").toString().trim().replace(" ","+")));
        nameValues.add(new BasicNameValuePair("req_time", BodyValue.get("req_time").toString().trim()));
        nameValues.add(new BasicNameValuePair("waimai_sign", BodyValue.get("waimai_sign").toString().trim())); //有可能会被编码为 %2F
        nameValues.add(new BasicNameValuePair("wm_longitude", BodyValue.get("wm_longitude").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_latitude", BodyValue.get("wm_latitude").toString().trim()));
        nameValues.add(new BasicNameValuePair("longitude", BodyValue.get("longitude").toString().trim()));
        nameValues.add(new BasicNameValuePair("latitude", BodyValue.get("latitude").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_actual_longitude", BodyValue.get("wm_actual_longitude").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_actual_latitude", BodyValue.get("wm_actual_latitude").toString().trim()));
        nameValues.add(new BasicNameValuePair("userid", BodyValue.get("userid").toString().trim()));
        nameValues.add(new BasicNameValuePair("user_id", BodyValue.get("user_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("wx_union_id", BodyValue.get("wx_union_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("avatarUrl", BodyValue.get("avatarUrl").toString().trim()));
        nameValues.add(new BasicNameValuePair("nickName", BodyValue.get("nickName").toString().trim()));
        nameValues.add(new BasicNameValuePair("open_id", BodyValue.get("open_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("openidcipher", BodyValue.get("openidcipher").toString().trim().replace(" ","+")));
        nameValues.add(new BasicNameValuePair("uuid", BodyValue.get("uuid").toString().trim()));
        nameValues.add(new BasicNameValuePair("rc_platform", BodyValue.get("rc_platform").toString().trim()));
        nameValues.add(new BasicNameValuePair("platform", BodyValue.get("platform").toString().trim()));
        nameValues.add(new BasicNameValuePair("rc_app", BodyValue.get("rc_app").toString().trim()));
        nameValues.add(new BasicNameValuePair("partner", BodyValue.get("partner").toString().trim()));
        nameValues.add(new BasicNameValuePair("riskLevel", BodyValue.get("riskLevel").toString().trim()));
        nameValues.add(new BasicNameValuePair("client_id", BodyValue.get("client_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("biz_id", BodyValue.get("biz_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("wm_poi_id", BodyValue.get("wm_poi_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("poi_id_str", BodyValue.get("poi_id_str").toString().trim()));

        if(!Objects.isNull(BodyValue.get("trace_tag"))) {
            nameValues.add(new BasicNameValuePair("trace_tag", BodyValue.get("trace_tag").toString().trim()));
        }
        nameValues.add(new BasicNameValuePair("need_spu_count_cut", BodyValue.get("need_spu_count_cut").toString().trim()));
        nameValues.add(new BasicNameValuePair("extra", BodyValue.get("extra").toString().trim()));
        nameValues.add(new BasicNameValuePair("team_id", BodyValue.get("team_id").toString().trim()));
        nameValues.add(new BasicNameValuePair("fingerprint", BodyValue.get("fingerprint").toString().trim()));
        nameValues.add(new BasicNameValuePair("_token", BodyValue.get("_token").toString().trim()));


        System.out.println("baseUrl:"+baseUrl);
        System.out.println("打印Headers值【】========================================");
        for (int i=0;i<Headers.length;i++){
            System.out.println(Headers[i]);
        }
        System.out.println("打印nameValues值【】========================================");
        System.out.println("nameValues:"+nameValues);

        return HttpPost(baseUrl,Headers,nameValues);
    }

    /**
     * 处理服务器返回菜单数据
     */
    public static void ProccessSrvResponseByItem(
            String SrvResponse,
            FirstclassService firstclassService,
            SecondclassService secondclassService)
    {
        if(SrvResponse.indexOf("成功")!=-1){
            try{
                JSONObject jsData=JSONObject.parseObject(SrvResponse); //将服务返回数据转换为json
                //获取一级菜单名称和id
                List<String> getItemList=getItemList(SrvResponse,secondclassService);
                System.out.println("一级菜单名称getItemList:"+getItemList);
                //1、先读取一次店铺数据库，若数值已存在则不插入(优化)
                List<Firstclass> getFirstClassByBrandName=firstclassService.getFirstClassByBrandName(StoreName);
                //循环读取数据
                List<Firstclass> firstClassData=new ArrayList<>();
                getItemList.forEach(item->{
                    JSONObject jobj = JSONObject.parseObject(item);
                    String itemId=jobj.getString("tag");
                    String itemName=jobj.getString("name");
                    String itemBrand=jobj.getString("brand");
                    if(getFirstClassByBrandName!=null && CheckValueForFirstList(itemName,getFirstClassByBrandName)==false) { //检查值是否已存在a false不存在
                        Firstclass firstclass = new Firstclass();
                        firstclass.setFirstid(itemId); //菜单id
                        firstclass.setFirstname(itemName); //菜单名称
                        firstclass.setBrandname(itemBrand);//店铺名称
                        firstClassData.add(firstclass);
                    }
                    //System.out.println(jobj.getString("name"));
                });
                //2、批量插入数据库
                if(firstClassData.size()>0) { //有数据再执行插入操作
                    firstclassService.saveBatch(firstClassData);
                }
            }catch (Exception ex){}
        }
    }


    /**
     * 获取一级表单数据
     */
    public static List<String> getItemList(String JsonString,SecondclassService secondclassService) {
        List<String> itemList=new ArrayList<>();
        JSONObject jsData=JSONObject.parseObject(JsonString); //将服务返回数据转换为json
        JSONObject data=JSONObject.parseObject(jsData.getString("data"));
        String food_spu_tags=data.getString("food_spu_tags");
        String poiInfo=data.getString("poi_info"); //读取店铺信息
        JSONObject poi=JSONObject.parseObject(poiInfo);
        String brandname=poi.getString("name");
        JSONArray jsonArray=JSONArray.parseArray(food_spu_tags);
        //开始遍历每个菜单
        for(int i=0;i<jsonArray.size();i++){
            JSONObject obj = jsonArray.getJSONObject(i); //{"name":"时令蔬菜","category_type":0,"tag":"new_op0080"}
            System.out.println("每条菜单:"+obj);
            String name=obj.getString("name");
            String id=obj.getString("tag");
            String keyVal="{\"name\":\""+name+"\",\"tag\":\""+id+"\",\"brand\":\""+brandname+"\"}";
            itemList.add(keyVal); //一级菜单名称
            //传入二级菜单字符
            if(!Objects.isNull(obj.getString("tags")) && !StringUtils.isEmpty(obj.getString("tags"))){
                getSubItemList(id,obj.getString("tags"),secondclassService);
            }
        }
        return itemList;
    }

    /**
     * 获取二级级表单数据
     * @param parentId 父元素字符串
     */
    public static List<String> getSubItemList(String parentId,String JsonString,SecondclassService secondclassService) {
        List<String> itemList=new ArrayList<>();
        JSONArray jsonArray=JSONArray.parseArray(JsonString);
        //开始遍历每个菜单
        for(int i=0;i<jsonArray.size();i++){
            JSONObject obj = jsonArray.getJSONObject(i); //{"name":"时令蔬菜","category_type":0,"tag":"new_op0080"}
            System.out.println("每条菜单:"+obj);
            String name=obj.getString("name");
            String id=obj.getString("tag");
            String keyVal="{\"parentId\":\""+parentId+"\",\"name\":\""+name+"\",\"tag\":\""+id+"\",\"brand\":\""+StoreName+"\"}";
            itemList.add(keyVal); //一级菜单名称
        }
        System.out.println("二级菜单名称==========================》:"+itemList);
        List<Secondclass> secondClassData=new ArrayList<>();
        //1、先读取一次店铺数据库，若数值已存在则不插入(优化)
        List<Secondclass> getSecondClassByBrandName=secondclassService.getSecondClassByBrandName(StoreName);
        itemList.forEach(item->{
            JSONObject subobj=JSONObject.parseObject(item);
            //System.out.println(jobj.getString("name"));
            String subName=subobj.getString("name");
            String subId=subobj.getString("tag");
            if(getSecondClassByBrandName!=null && CheckValueForSecondList(subName,getSecondClassByBrandName)==false) { //检查值是否已存在a false不存在
                Secondclass secondClass = new Secondclass();
                secondClass.setFirstid(parentId); //菜单id
                secondClass.setSecondid(subId); //菜单名称
                secondClass.setSecondname(subName);
                secondClass.setBrandname(StoreName);//店铺名称
                secondClassData.add(secondClass);
            }
        });
        //2、批量插入数据库
        if(secondClassData.size()>0) { //有数据再执行插入操作
            secondclassService.saveBatch(secondClassData);
        }
        return itemList;
    }

    /**
     * 检查第一类目的值是否已存在List中
     * @param List<Firstclass> 列表元素
     */
    public static Boolean CheckValueForFirstList(String itemName,List<Firstclass> firstclassLists) {
        boolean isExist=false;
        Pattern pattern=Pattern.compile(itemName);
        for(int i=0;i<firstclassLists.size();i++){
            Matcher matcher=pattern.matcher(firstclassLists.get(i).getFirstname());
            if(matcher.matches()){
                isExist=true;
                break;
            }
        }
        return isExist;
    }

    /**
     * 检查第二类目的值是否已存在List中
     * @param List<Firstclass> 列表元素
     */
    public static Boolean CheckValueForSecondList(String itemName,List<Secondclass> secondclassLists) {
        boolean isExist=false;
        Pattern pattern=Pattern.compile(itemName);
        for(int i=0;i<secondclassLists.size();i++){
            Matcher matcher=pattern.matcher(secondclassLists.get(i).getSecondname());
            if(matcher.matches()){
                isExist=true;
                break;
            }
        }
        return isExist;
    }




    /**
     * 处理服务器，返回产品数据
     */
    public static void ProccessSrvResponseByProduct(
            String SrvResponse,
            SavedataService savedataService)
    {
        if(SrvResponse.indexOf("成功")!=-1){
            try{
                JSONObject jsData=JSONObject.parseObject(SrvResponse); //将服务返回数据转换为json
                //获取一级菜单名称和id
                JSONObject data=JSONObject.parseObject(jsData.getString("result"));
                String ProductsContent=data.getString("searchCatResultVOList"); //searchCatResultVOList

                /*jsData=JSONObject.parseObject(ProductsContent);
                data=JSONObject.parseObject(jsData.getString("searchResultVOList"));
                ProductsContent=data.getString("searchResultVOList");*/

                System.out.println("=========================");
                System.out.println("开始处理数据");
                ProductsContent=ProductsContent.substring(1,ProductsContent.length()-1);
                data=JSONObject.parseObject(ProductsContent);
                ProductsContent=data.getString("searchResultVOList");
                //System.out.println(ProductsContent);

                List<Savedata> analyzeItemList=analyzeItem(ProductsContent,savedataService); //分析产品结构并写入数据
            }catch (Exception ex){}
        }
    }

    /**
     * 检查产品名称的值是否已存在List中
     * @param List<Products> 列表元素
     */
    public static Boolean CheckValueForProductList(String itemName,List<Savedata> ProductsLists) {
        boolean isExist=false;
        Pattern pattern=Pattern.compile(itemName);
        for(int i=0;i<ProductsLists.size();i++){
            Matcher matcher=pattern.matcher(ProductsLists.get(i).getSname());
            if(matcher.matches()){
                isExist=true;
                break;
            }
        }
        return isExist;
    }




    /**
     * 根据二级id 返回二级名称
     */

    /**
     * 分析菜单内容，保存
     * 传入 product_spu_list
     */
    public static List<Savedata> analyzeItem(
            String inputString,
            SavedataService savedataService
    ) throws SQLDataException {
        JSONArray dataArray=JSONArray.parseArray(inputString);
        //1、先读取一次店铺数据库，若数值已存在则不插入(优化)
        List<Savedata> SavedDatasList=new ArrayList<>();

        //System.out.println("开始分析数据========");

        for(int i=0;i<dataArray.size();i++){

            System.out.println(dataArray.get(i).toString()+"\n");

            JSONObject item=JSONObject.parseObject(dataArray.get(i).toString());
            String pdataid=item.get("storeId").toString();
            String pname=item.get("skuName").toString();
            String desc=item.get("realTimePrice").toString(); //8.7折 限1份;
            String pimgurl=item.get("imgUrl").toString(); //封面图
            String price=item.get("realTimePrice").toString(); //价格
            String sellnumber=item.get("stockCount").toString(); //月销量

            //数据表映射字段
            Savedata products = new Savedata();
            products.setSdataid(pdataid);
            products.setSname(pname);
            products.setSdec(desc);
            products.setSpic(pimgurl);
            products.setSprice(price);
            products.setSellnumber(sellnumber);
            products.setSbrand(StoreName);

            SavedDatasList.add(products); //添加到集合
        }
        System.out.println("查看SavedDatasList:"+SavedDatasList+"大小size:"+SavedDatasList.size());
        //2、批量插入数据库
        if(SavedDatasList.size()>0) { //有数据再执行插入操作
            savedataService.saveBatch(SavedDatasList);
        }
        return SavedDatasList;
    }





    /**
     * 屏幕截图函数
     *         // 获取鼠标位置
     *         Point point = MouseInfo.getPointerInfo().getLocation();
     *         // 输出光标的横坐标和纵坐标
     *         System.out.println("光标位置：x = " + point.x + ", y = " + point.y);
     *         SpiderTools.screenShot("222",point,180,25);
     */

    public static String screenShot(String FolderName,Point point,int RectWidth,int RectHeight,String mode,boolean isFullPath) {
        Rectangle screenRectangle;//根据屏幕大小创建一个矩形
        if(!Objects.isNull(point)){
            if(point.x<350){
                int x=mode.equals("大标题")?(int)(point.x-100):(int)(point.x-50);
                int y=mode.equals("大标题")?(int)(point.y-15):point.y-15;
                System.out.println("x:"+x+",y:"+y);
                screenRectangle = new Rectangle(x,y,RectWidth,RectHeight);
            }else{
                int x=(int)(point.x-100); //point.x-point.x*0.065
                int y=point.y-10;
                System.out.println("x:"+x+",y:"+y);
                screenRectangle = new Rectangle(x,y,RectWidth,RectHeight);
            }
        }else{
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕大小
            screenRectangle = new Rectangle(screenSize);//根据屏幕大小创建一个矩形
        }

        System.out.println("当前矩形大小"+screenRectangle.getWidth()+","+screenRectangle.getHeight());

        String randomName = UUID.randomUUID().toString().replace("-", "");
        String name = randomName + ".png";//jpg等也可
        // 截图保存的路径
        File screenFile = new File("src/main/resources/static/images/screenShot/"+FolderName);
        if (!screenFile.exists()) {
            screenFile.mkdirs();//创建文件路径
        }
        Robot robot;
        String path = "";
        boolean b = false;
        try {
            robot = new Robot();
            BufferedImage image = robot.createScreenCapture(screenRectangle);//使用Robot类提供的截屏方法，
            File f = new File(screenFile, name);
            b = ImageIO.write(image, "png", f);
        } catch (Exception e) {

        }
        if (b) {
            if(isFullPath){
                path ="src/main/resources/static/images/screenShot/"+ FolderName + File.separator + name;
            }else{
                path = name;
            }
        }
        return path;
    }


    /**
     * 美团菜单屏幕截图函数
     *         // 获取鼠标位置
     *         Point point = MouseInfo.getPointerInfo().getLocation();
     *         // 输出光标的横坐标和纵坐标
     *         System.out.println("光标位置：x = " + point.x + ", y = " + point.y);
     *         SpiderTools.screenShot("222",point,180,25);
     */

    public static String meituanScreenShot(String FolderName,Point point,int RectWidth,int RectHeight,boolean isFullScreen,boolean isFullPath) {
        Rectangle screenRectangle=null;//根据屏幕大小创建一个矩形
        if(!Objects.isNull(point)){
            if(isFullScreen==false){
                //指定范围
                screenRectangle = new Rectangle(point.x,point.y,RectWidth,RectHeight);
            }else{
                //全屏
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕大小
                screenRectangle = new Rectangle(screenSize);//根据屏幕大小创建一个矩形
            }
            //System.out.println("当前矩形大小"+screenRectangle.getWidth()+","+screenRectangle.getHeight());
        }
        String randomName = UUID.randomUUID().toString().replace("-", "");
        String name = randomName + ".png";//jpg等也可
        // 截图保存的路径
        File screenFile = new File("src/main/resources/static/images/screenShot/imgFile/"+FolderName);
        if (!screenFile.exists()) {
            screenFile.mkdirs();//创建文件路径
        }
        Robot robot;
        String path = "";
        boolean b = false;
        try {
            robot = new Robot();
            BufferedImage image = robot.createScreenCapture(screenRectangle);//使用Robot类提供的截屏方法，
            File f = new File(screenFile, name);
            b = ImageIO.write(image, "png", f);
        } catch (Exception e) {

        }
        if (b) {
            if(isFullPath){
                path ="src/main/resources/static/images/screenShot/"+ FolderName + File.separator + name;
            }else{
                path = name;
            }
        }
        return path;
    }





    /**
     * 读取请求流
     * @param request
     *
     * System.out.println("读取========>");
     *         System.out.println(ReadFilterChange(request));
     *         System.out.println("<========读完");
     */
    public static String ReadFilterChange(HttpServletRequest request) {
        try (BufferedReader reader = request.getReader()) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MyHttpServletRequestWrapper.RequestReadUtils.read 获取请求流异常");
        }
    }


}
